<?php
namespace App\Http\Controllers\Admin\Qudao;

use App\Service\Admin\Qudao\SucaiService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;

class SucaiController extends BaseController
{
    //素材

    public function __construct(SucaiService $service)
    {
        $this->db = $service;
    }

    //列表
    public function getIndex()
    {
        $res = $this->db->getList();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //详情
    public function getOne(Request $request)
    {
        $id = $request->post('id', 0);
        $res = $this->db->getOne($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //更新
    public function modify(Request $request)
    {
        $id = $request->post('id', 0);
        $gno = $request->post('gno', '');
        $pas['title'] = $request->post('title', '');
        $pas['detail'] = $request->post('detail', '');
        if (!$pas['title']) {
            return $this->toJson(-2, '标题必须的');
        }
        if ($id) {
            $res = $this->db->modify($id, $gno, $pas);
        } else {
            $res = $this->db->add($gno, $pas);
        }
        if ($res['code'] < 0) {
            return $this->toJson($res['code'], $res['msg']);
        }
        return $this->toJson();
    }

    //上传
    public function upload(Request $request)
    {
        $scid = $request->post('scid', 0);
        $img = $request->post('img', '');
//        if (!$scid) {
//            return $this->toJson(-2, 'ID必须的');
//        }
        if (!$img) {
            return $this->toJson(-2, '图片必须的');
        }
        $fpath = Upload::getPathByBase64($img);
        $sizes = getimagesize($img);
        $res = $this->db->addImg($scid, $fpath, $sizes[0], $sizes[1]);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //删除
    public function del(Request $request)
    {
        $id = $request->post('id', 0);
        if (!$id) {
            return $this->toJson(-2, 'ID必须的');
        }
        $res = $this->db->setDel($id);
        if ($res['code'] < 0) {
            return $this->toJson($res['code'], $res['msg']);
        }
        return $this->toJson();
    }
}